package common;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import model.exceptions.InvalidNameException;

public enum Persistence
{

  INSTANCE;

  public static Result save(Object object, String name) throws IOException, InvalidNameException
  {
    if (object == null)
    {
      return new Result(false, "Null object.");
    }
    if (name == "" || name == null)
    {
      throw new InvalidNameException("Null/Empty name.");
    }
    BufferedOutputStream outFile = new BufferedOutputStream(new FileOutputStream(name + ".ser"));
    ObjectOutputStream output = new ObjectOutputStream(outFile);
    output.writeObject(object);
    output.close();
    return new Result(true);
  }

  public static Object load(String name) throws InvalidNameException, ClassNotFoundException,
      IOException
  {
    if (name == "" || name == null)
    {
      throw new InvalidNameException("Null/Empty name.");
    }
    BufferedInputStream inFile;
    ObjectInputStream input;
    Object object;
    inFile = new BufferedInputStream(new FileInputStream(name + ".ser"));
    input = new ObjectInputStream(inFile);
    object = input.readObject();
    input.close();
    return object;
  }
}
